package ro.pub.cs.client;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.user.client.History;
import com.google.gwt.user.client.HistoryListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.VerticalPanel;

public class LeftMenu extends Composite implements HistoryListener {
	private static final String CHECKER_TOKEN = "Checker";
	private static final String GRADES_TOKEN = "Grades";
	private static final String SETTINGS_TOKEN = "Settings";
	
	public interface SelectionListener {
		void onCheckerSelected();
		void onGradesSelected();
		void onHomeworkSelected(String token);
		void onSettingsSelected();
	}
	
	private SelectionListener selectionListener = null;
	
	private VerticalPanel panel = new VerticalPanel();
	
	private List<Hyperlink> hwLinks = new ArrayList<Hyperlink>();
	
	private Hyperlink checkerLink = new Hyperlink("Checker", CHECKER_TOKEN);
	private Hyperlink gradesLink = new Hyperlink("Grades", GRADES_TOKEN);
	
	private Hyperlink settingsLink = new Hyperlink("Settings", SETTINGS_TOKEN);
	
	public LeftMenu(SelectionListener clickListener) {
		this.selectionListener = clickListener;
		
		panel.setSpacing(3);
		panel.add(checkerLink);
		panel.add(gradesLink);
		
		panel.add(settingsLink);
		
		initWidget(panel);
		
		History.addHistoryListener(this);
	}
	
	public void selectInitial() {
		String initialToken = History.getToken();
		if (initialToken.length() == 0)
			initialToken = hwLinks.get(0).getTargetHistoryToken();
		
		onHistoryChanged(initialToken);
	}
	
	public Hyperlink getCheckerLink() {
		return checkerLink;
	}
	
	public Hyperlink getGradesLink() {
		return gradesLink;
	}
	
	public Hyperlink getSettingsLink() {
		return settingsLink;
	}
	
	public void addHomeworkLink(String label, String token) {
		Hyperlink newLink = new Hyperlink(label, token);
		
		hwLinks.add(newLink);
		
		panel.insert(newLink, hwLinks.size()-1);
	}
	
	public Hyperlink getHomeworkLink(int index) {
		return hwLinks.get(index);
	}

	public void onHistoryChanged(String historyToken) {
		if (historyToken.equals(CHECKER_TOKEN)) {
			selectionListener.onCheckerSelected();
		} else if (historyToken.equals(GRADES_TOKEN)) {
			selectionListener.onGradesSelected();
		} else if (historyToken.equals(SETTINGS_TOKEN)){
			selectionListener.onSettingsSelected();
		} else {
			selectionListener.onHomeworkSelected(historyToken);
		}
		
	}
}
